package com.tqjc.area.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tqjc.area.entity.Article;
import com.tqjc.area.entity.SteelPlate;
import com.tqjc.area.entity.VO.SteelLoadVO;
import com.tqjc.area.service.SteelPlateService;
import com.tqjc.area.wrapper.SteelPlateWrapper;
import com.tqjc.execute.task.entity.Task;
import com.tqjc.execute.utils.ExcelUtils;
import com.tqjc.system.core.model.AjaxJson;
import com.tqjc.system.core.model.PageInfo;
import com.tqjc.system.core.query.QueryUtils;
import com.tqjc.system.core.util.DateUtils;
import com.tqjc.system.core.util.ResponseUtil;
import com.tqjc.system.system.entity.SysUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Executable;
import java.util.Date;
import java.util.List;

/**
 * @projectName: BaotouSteel
 * @package: com.tqjc.area.controller
 * @className: SteelController
 * @author: Patienyon
 * @description: TODO
 * @date: 2023/7/2 23:54
 * @version: 1.0
 */

@Controller
@RequestMapping("/steel")
@Slf4j
public class SteelPlateController {

    @Resource
    SteelPlateService steelPlateService;


    //钢板管理主页
    @RequestMapping("/index")
    public String index() {
        return "baotou-steel/AreaManage/SteelPlateManage.html";
    }


    @RequestMapping("/uploadExcel")
    @ResponseBody
    public AjaxJson uploadExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), Article.class, new PageReadListener<Article>(dataList -> {
                for (Article demoData : dataList) {
                    log.info("读取到一条数据{}", "姓名：" + demoData.getName() + " 文章：" + demoData.getTitle() + " 得分:" + demoData.getScore());
                }
            })).sheet().doRead();

            AjaxJson j = new AjaxJson();
            return j;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return AjaxJson.fail("上传失败");
    }


    /**
     *  获取表格数据 树形结构
     * @param
     * @param request
     * @return
     */
    @RequestMapping("/datagrid")
    @ResponseBody
    public void datagrid(SteelLoadVO steelLoadVO, PageInfo<SteelPlate> page, HttpServletRequest request, HttpServletResponse response) {

        try {

            //拼接查询条件
        /*QueryWrapper<SteelPlate> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(steelPlate.getAreaId())) {
            log.info("stock area id="+steelPlate.getAreaId());
            queryWrapper.eq("area",  "stock_" + steelPlate.getAreaId());
        }*/
//            QueryWrapper<SteelPlate> queryWrapper = QueryUtils.installQueryWrapperRow(steelPlate, request.getParameterMap());
            formatDate(steelLoadVO);
            LambdaQueryWrapper<SteelPlate> queryWrapper = new LambdaQueryWrapper<SteelPlate>()
                    .le(steelLoadVO.getMinCreateTime() != null, SteelPlate::getCreateDate, steelLoadVO.getMaxCreateTime())
                    .ge(steelLoadVO.getMinCreateTime() != null, SteelPlate::getCreateDate, steelLoadVO.getMinCreateTime())
                    .eq(StringUtils.isNotEmpty(steelLoadVO.getArea()), SteelPlate::getArea, steelLoadVO.getArea())
                    .orderByDesc(SteelPlate::getCreateDate);

            //执行查询
            IPage<SteelPlate> lstResult =steelPlateService.page(page.getPageEntity(), queryWrapper);

            //结果处理,直接写到客户端
            ResponseUtil.write(response, new SteelPlateWrapper(lstResult).wrap());

        } catch (Exception e){
            log.error("查询板坯信息出现异常",e);
        }

    }

    /**
     *  获取表格数据 树形结构
     * @param
     * @param request
     * @return
     */
    @RequestMapping("/load")
    @ResponseBody
    public void load(SteelLoadVO steelLoadVO, HttpServletRequest request, HttpServletResponse response) {

        log.info("文件下载开始");
        try( ServletOutputStream outputstream = response.getOutputStream();
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            formatDate(steelLoadVO);
            List<SteelPlate> list =  steelPlateService.getLoadList(steelLoadVO);

            if(CollectionUtil.isEmpty(list)){

                log.warn("文件下载功能中，当前无数据集合需要下载");
                return;
            }


            XSSFWorkbook wb = new XSSFWorkbook();
            //构建Workbook 数据
            ExcelUtils.buildData(wb, list);
            //设置Workbook 格式
            ExcelUtils.buildStyle(wb);

            //到这里，excel就已经生成了，然后就需要通过流来写出去

            //将excel写入流
            wb.write(byteArrayOutputStream);

            String fileName = ExcelUtils.getFileName();

            //设置返回的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //对文件编码
            fileName = response.encodeURL(new String(fileName.getBytes("gb2312"), "iso8859-1"));
            //使用Servlet实现文件下载的时候，避免浏览器自动打开文件
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);


            //设置文件大小
            response.setContentLength(byteArrayOutputStream.size());
            //将流写进response输出流中

            byteArrayOutputStream.writeTo(outputstream);

            outputstream.flush();

        } catch (Exception e){
            log.error("文件下载出现异常",e);

        }
        log.info("文件下载完成");



    }

    private void formatDate(SteelLoadVO steelLoadVO){

        if(StringUtils.isNotEmpty(steelLoadVO.getCreateTimeStr())){
            steelLoadVO.setMinCreateTime(DateUtils.getLocalDateTime(steelLoadVO.getCreateTimeStr() + " 00:00:00"));
            steelLoadVO.setMaxCreateTime(DateUtils.getLocalDateTime(steelLoadVO.getCreateTimeStr() + " 23:59:59"));
        }

    }


}
